$(function (){

    let num = 0 , nums = 0;
    $(".addListB p").click(async function (){
        num++;
        let str = '';
        str = `
            <div class="templet">
                <div class="parseInset" style="margin-top: 10px;width: 100%;display:table;position: relative">
                    <div class="taskName col-sm-6" style="padding-left: 0">
                      <input name="topicName" class="form-control" autocomplete="off" type="text" placeholder="请输入名称">
                    </div>
                    <div class="taskScore col-sm-6" style="padding-left: 0;padding-right: 0">
<!--                    onkeyup= "this.value=this.value.replace(/[^\\d]/g,'')"-->
                      <input name="score" class="form-control" type="text" autocomplete="off" placeholder="请输入分数" >
                    </div>
                    <div class="taskDesc col-sm-12" style="padding-left: 0;padding-right: 0">
                      <textarea name="description" class="form-control" autocomplete="off" type="text" placeholder="请输入题目描述"></textarea>
                    </div>
                    <div class="remove">删除</div>
                </div>
                <div id="refer${num}"></div>  
               <select class="form-control query" name="" style="margin-top: 10px">
        `;

        let templet = await getModuleEntrance();
        templet.data?.map(function (v,k){
            str += `
                    <option style="${k == 0 ? '':'display:none'}">请选择题目细则</option>
                    <option value="${v.id}">${v.detailContent}</option>
            `;
        })

        str += `</select></div>`;

        $("#addParams").append(str);

        alltion = await allocation();
        alltion = alltion.data.map(function (v) {
            if( v ){
                v.selected = false;
                v.value = v.id;
            }
            return v;
        })

        xmSelect.render({
            el: '#refer'+ num,
            autoRow: true,
            name: 'refer'+ num,
            // max:3,
            data() {
                return alltion
            },
            maxMethod(seles, item) {
                layer.msg(`最多只能选择3个`)
            },
            on: function (data) {

                // for(var i = 0; i < refereesc.length; i++){
                //     if( refereesc[i].id == data.change[0].id ){
                //         layer.msg('该裁判已分配在其他列表')
                //         return false;
                //     }
                // }

                let arr = [];
                refereesb = data.arr;
                data.arr.map(function (v){
                    arr.push(v.id);
                })
                $("input[name='refer"+ num +"']").val(arr.join(','));
            }
        })

    })

    $(".addListC p").click(async function (){
        nums++;
        let str = '';
        str = `
            <div class="templet">
                <div class="parseInset" style="margin-top: 10px;width: 100%;display:table;position: relative">
                    <div class="taskName col-sm-6" style="padding-left: 0">
                      <input name="topicName" class="form-control" autocomplete="off" type="text" placeholder="请输入名称">
                    </div>
                    <div class="taskScore col-sm-6" style="padding-left: 0;padding-right: 0">
<!--                    onkeyup= "this.value=this.value.replace(/[^\\d]/g,'')"-->
                      <input name="score" class="form-control" autocomplete="off" type="text" placeholder="请输入分数" >
                    </div>
                    <div class="taskDesc col-sm-12" style="padding-left: 0;padding-right: 0">
                        <textarea name="description" class="form-control" autocomplete="off" type="text" placeholder="请输入题目描述"></textarea>
                      </div>
                    <div class="remove">删除</div>
                </div>
                 <div id="refers${nums}"></div>
                 <select class="form-control query" name="" style="margin-top: 10px">
        `;

        let templet = await getModuleEntrance();
        templet.data?.map(function (v,k){
            str += `
                    <option style="${k == 0 ? '':'display:none'}">请选择题目细则</option>
                    <option value="${v.id}">${v.detailContent}</option>
                `;
        })

        str += `</select></div>`;

        $("#addField").append(str);
        alltion = await allocation();
        alltion = alltion.data.map(function (v) {
            if( v ){
                v.selected = false;
                v.value = v.id;
            }
            return v;
        })

        xmSelect.render({
            el: '#refers'+ nums,
            autoRow: true,
            name: 'refers'+ nums,
            // max:3,
            data() {
                return alltion
            },
            maxMethod(seles, item) {
                layer.msg(`最多只能选择3个`)
            },
            on: function (data) {
                // for(var i = 0; i < refereesb.length; i++){
                //     if( refereesb[i].id == data.change[0].id ){
                //         layer.msg('该裁判已分配在其他列表')
                //         return false;
                //     }
                // }
                // refereesc = data.arr;
                let arrb = [];
                data.arr.map(function (v){
                    arrb.push(v.id);
                })
                $("input[name='refers"+ nums +"']").val(arrb.join(','));
            }
        })
    })

    $("body").on('click','.remove',function (){
        $(this).parents('.templet').remove();
    })

    $("#btn").click(function (){
        save();
    })

    function save() {

        let disposition = [];

        // $(".templet").each(function (index,val){
        //     if(!$(val).find('.query').val()){
        //         layer.msg('请选择题目细则')
        //         return false;
        //     }

            // $("#addParams").find(".templet").each(function (index,val){
            //     if(!$(val).find('.query').val()){
            //         layer.msg('请选择题目细则')
            //         return false;
            //     }
            //     disposition.push({
            //         topicName: $(val).find('.taskName').find('input').val(),
            //         score: $(val).find('.taskScore').find('input').val(),
            //         description: $(val).find('.taskDesc').find('textarea').val(),
            //         refereeId:$(val).find('input[name="refer'+index+'"]').val(),
            //         detailId:$(val).find('.query').val(),
            //         moduleId: window.location.href.split('/')[5],
            //         type:'B'
            //     })
            // })


            // if( $(val).parents('#addField') ){
            //     disposition.push({
            //         topicName: $(val).find('.taskName').find('input').val(),
            //         score: $(val).find('.taskScore').find('input').val(),
            //         description: $(val).find('.taskDesc').find('textarea').val(),
            //         refereeId:$(val).find('input[name="refers'+index+'"]').val(),
            //         detailId:$(val).find('.query').val(),
            //         moduleId: window.location.href.split('/')[5],
            //         type:'C'
            //     })
            // }


        // })

        let indextb = 0;
        $("#addParams").find(".templet").each(function (index,val){
            if(!$(val).find('.query').val()){
                layer.msg('请选择题目细则')
                return false;
            }
            disposition.push({
                id:$(val).find('.moduleId').val(),
                topicName: $(val).find('.taskName').find('input').val(),
                score: $(val).find('.taskScore').find('input').val(),
                description: $(val).find('.taskDesc').find('textarea').val(),
                refereeId:$('input[name="refer'+indextb+'"]').val(),
                detailId:$(val).find('.query').val(),
                moduleId: window.location.href.split('/')[5],
                type:'B'
            })
            indextb++;
        })

        $("#addField").find(".templet").each(function (index,val){
            if(!$(val).find('.query').val()){
                layer.msg('请选择题目细则')
                return false;
            }
            disposition.push({
                id:$(val).find('.moduleId').val(),
                topicName: $(val).find('.taskName').find('input').val(),
                score: $(val).find('.taskScore').find('input').val(),
                description: $(val).find('.taskDesc').find('textarea').val(),
                refereeId:$('input[name="refers'+indextb+'"]').val(),
                detailId:$(val).find('.query').val(),
                moduleId: window.location.href.split('/')[5],
                type:'C'
            })
            indextb++;
        })

        let maximum = 0;
        for(let i = 0; i <= disposition.length - 1; i++ ){

            if( !disposition[i].detailId  ||  disposition[i].detailId == "请选择题目细则"){
                layer.msg('请选择题目细则');
                return false;
            }

            maximum += parseFloat(disposition[i].score);
            // console.log(maximum);
            if( disposition[i].topicName == '' ){
                layer.msg('请填写题目名称');
                return false;
            }

            if( disposition[i].description == '' ){
                layer.msg('请填写题目描述');
                return false;
            }

            if( disposition[i].score == '' ){
                layer.msg('请填写分数');
                return false;
            }

        }

        if(maximum > $("#topicScore").val()){
            layer.msg('模块分值不能超过模版总分或小于0');
            return false;
        }

        if( maximum <= 0 ){
            layer.msg('模块分值不能超过模版总分或小于0');
            return false;
        }

        if( !$('#moduleName').val() ||  !$("#moduleType").val()){
            layer.msg('请输入名称或考试类型');
            return false;
        }

        if( !$('#competitionType').val() ){
            layer.msg('请选择竞赛类型');
            return false;
        }

        // disposition = JSON.stringify(disposition);

        let response = {
            id:window.location.href.split('/')[5],
            moduleName: $('#moduleName').val(),
            moduleType: $("#moduleType").val(),
            dispositionTopic: disposition,
            totalScore: $("#topicScore").val(),
            competitionType: $("#competitionType").val()
        }

        response = JSON.stringify(response);

        $.ajax({
            cache: true,
            type: "POST",
            url: "/jz-jinzhuan-disposition-module/updateModuleById",
            data: response,// 你的formid
            async: false,
            headers: {
                'Content-Type':'application/json;charset=UTF-8'
            },
            error: function (request) {
                parent.layer.alert("Connection error");
            },
            success: function (data) {
                if (data.code == 0) {
                    parent.layer.msg("操作成功");
                    parent.reLoad();
                    var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                    parent.layer.close(index);

                } else {
                    parent.layer.alert(data.msg)
                }

            }
        });


    }

    function getModuleEntrance(){
        return $.ajax({
            cache: true,
            type: "post",
            url: "/jz-jinzhuan-disposition-module/selectModuleDetail",
            contentType:'application/json; charset=utf-8',
            async: false,
            error: function (request) {
                parent.layer.alert("Connection error");
            },
            success: function (data) {

            }
        })
    }

    function allocation(){
        let maps = {
            track: '',
            competitionType: sessionStorage.getItem('dtype')
        };

        //选择裁判
        return $.ajax({
            cache: true,
            type: "post",
            url: "/jzweb/examinationBatchCom/getUserReferee",
            contentType:'application/json; charset=utf-8',
            data: JSON.stringify(maps),
            async: false,
            error: function (request) {
                parent.layer.alert("Connection error");
            },
            success: function (data) {
                if (data.code == 0) {
                    var format = [];

                    format = data.data.map(function (v) {
                        if( v ){
                            v.selected = false;
                            v.value = v.id;
                        }
                        return v;
                    })
                    return format;
                }
            }
        })
    }

    let response = {
        id:window.location.href.split('/')[5]
    }
    $.ajax({
        cache: true,
        type: "POST",
        url: "/jz-jinzhuan-disposition-module/updateModuleDate",
        data: JSON.stringify(response),// 你的formid
        async: false,
        headers: {
            'Content-Type':'application/json;charset=UTF-8'
        },
        error: function (request) {
            parent.layer.alert("Connection error");
        },
        success:function (data) {
            let datas = data.data[0] , str = '' , srr = '' , refereesb = [] , refereesc = [];
            let templet = getModuleEntrance().responseJSON.data;
            let alltion = allocation().responseJSON.data;

            alltion = alltion?.map(function (v) {
                if( v ){
                    v.selected = false;
                    v.value = v.id;
                }
                return v;
            })

            if (data.code == 0) {
                $("#moduleName").val(datas.moduleName);
                $("#competitionType").val(datas.competitionType)
                $("#moduleType").val(datas.moduleType)
                $("#topicScore").val(datas.totalScore)
                datas.dispositionTopic?.map(function (list,k){
                    if(list.type == 'B'){
                        str += `
                          <div class="templet">
                            <div class="parseInset" style="width: 100%;display: table;">
                                <div class="taskName col-sm-6" style="padding-left: 0">
                                  <input name="topicName" class="form-control" type="text" placeholder="请输入名称" value="${list.topicName}">
                                </div>
                                <input type="hidden" class="moduleId" value="${list.id}">
                                <div class="taskScore col-sm-6" style="padding-left: 0;padding-right: 0">
<!--                                onkeyup= "this.value=this.value.replace(/[^\\d]/g,'')"-->
                                  <input name="score" class="form-control" type="text" placeholder="请输入分数"  value="${list.score}" >
                                </div>
                                <div class="taskDesc col-sm-12" style="padding-left: 0;padding-right: 0">
                                  <textarea name="description" class="form-control" type="text" placeholder="请输入题目描述">${list.description}</textarea>
                                </div>
                                <div class="remove">删除</div>
                            </div>
                            <div id="refer${k}" class="judge" style="margin-bottom: 10px"></div>
                            <select class="form-control query">
                        `;

                        templet?.map(function (val,ks){
                            if(ks == 0){
                                str += `<option>请选择题目细则</option>`
                            }
                            str += `
                                <option value="${val.id}" ${list.detailId == val.id ? 'selected':''}>${val.detailContent}</option>
                            `;
                        })

                        str += `</select></div>`;
                    }

                    if(list.type == 'C') {
                        srr += `
                          <div class="templet">
                            <div class="parseInset" style="width: 100%;display: table;">
                                <div class="taskName col-sm-6" style="padding-left: 0">
                                  <input name="topicName" class="form-control" type="text" placeholder="请输入名称" value="${list.topicName}">
                                </div>
                                <input type="hidden" class="moduleId" value="${list.id}">
                                <div class="taskScore col-sm-6" style="padding-left: 0;padding-right: 0">
<!--                                onkeyup= "this.value=this.value.replace(/[^\\d]/g,'')"-->
                                  <input name="score" class="form-control" type="text" placeholder="请输入分数"  value="${list.score}" >
                                </div>
                                <div class="taskDesc col-sm-12" style="padding-left: 0;padding-right: 0">
                                  <textarea name="description" class="form-control" type="text" placeholder="请输入题目描述" >${list.description}</textarea>
                                </div>
                                <div class="remove">删除</div>
                            </div>
                            <div id="refers${k}" class="judge" style="margin-bottom: 10px"></div>
                            <select class="form-control query">
                        `;

                        templet?.map(function (val,ks){
                            if(ks == 0){
                                srr += `<option>请选择题目细则</option>`
                            }
                            srr += `
                                <option value="${val.id}" ${list.detailId == val.id ? 'selected':''}>${val.detailContent}</option>
                            `;
                        })
                        srr += `</select></div>`;

                    }

                })

                $("#addParams").html(str)
                $("#addField").html(srr)

                datas.dispositionTopic?.map(function (v,k){
                    if(v.type == 'B') {
                        num = k;
                        xmSelect.render({
                            el: '#refer' + k,
                            autoRow: true,
                            name: 'refer' + k,
                            initValue: v.refereeId ? v.refereeId.split(',') : [],
                            // max:3,
                            data() {
                                return alltion
                            },
                            maxMethod(seles, item) {
                                layer.msg(`最多只能选择3个`)
                            },
                            on: function (data) {

                                for (var i = 0; i < refereesc.length; i++) {
                                    if (refereesc[i].id == data.change[0].id) {
                                        layer.msg('该裁判已分配在其他列表')
                                        return false;
                                    }
                                }
                                let arr = [];
                                refereesb = data.arr;
                                data.arr.map(function (v) {
                                    arr.push(v.id);
                                })
                                $("input[name='refer" + k + "']").val(arr.join(','));
                            }
                        })
                    }
                    if (v.type == 'C'){
                        nums = k;
                        xmSelect.render({
                            el: '#refers' + k,
                            autoRow: true,
                            name: 'refers' + k,
                            initValue: v.refereeId ? v.refereeId.split(',') : [],
                            // max:3,
                            data() {
                                return alltion
                            },
                            maxMethod(seles, item) {
                                layer.msg(`最多只能选择3个`)
                            },
                            on: function (data) {

                                for (var i = 0; i < refereesc.length; i++) {
                                    if (refereesc[i].id == data.change[0].id) {
                                        layer.msg('该裁判已分配在其他列表')
                                        return false;
                                    }
                                }
                                let arr = [];
                                refereesb = data.arr;
                                data.arr.map(function (v) {
                                    arr.push(v.id);
                                })
                                $("input[name='refers" + k + "']").val(arr.join(','));
                            }
                        })
                    }
                })

            } else {
                parent.layer.alert(data.msg)
            }

        }
    });


})
